package com.run_java_test.test7;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.PostConstruct;
import java.io.File;
import java.lang.reflect.Method;

@Component
public class ControllerRegistrar {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    private static final String CONTROLLER_DIR = "D:\\data\\com\\run_java_test";

    @PostConstruct
    public void registerControllers() {
        File controllerDir = new File(CONTROLLER_DIR);
        if (controllerDir.isDirectory()) {
            File[] files = controllerDir.listFiles((dir, name) -> name.endsWith(".class"));
            if (files != null) {
                for (File file : files) {
                    String className = file.getName().replace(".class", "");
                    try {
                        CustomClassLoader classLoader = new CustomClassLoader(CONTROLLER_DIR);
                        Class<?> clazz = classLoader.loadClass(className);
                        registerClass(clazz);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void registerClass(Class<?> clazz) {
        if (clazz.isAnnotationPresent(org.springframework.stereotype.Controller.class)) {
            try {
                // 创建控制器实例
                Object controllerInstance = applicationContext.getAutowireCapableBeanFactory().createBean(clazz);
                for (Method method : clazz.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);

                        // 创建 RequestMappingInfo
                        RequestMappingInfo mappingInfo = RequestMappingInfo
                                .paths(requestMapping.value())
                                .methods(requestMapping.method())
                                .produces(requestMapping.produces())
                                .consumes(requestMapping.consumes())
                                .build();

                        // 注册 HandlerMethod
                        requestMappingHandlerMapping.registerMapping(mappingInfo, controllerInstance, method);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
